package com.example.allshengmedical.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.allsheng.widget.AllShengDialog;
import com.allsheng.widget.AllShengDialog.ClickListenerInterface;
import com.example.allshengmedical.base.BaseApplication;
import com.example.allshengmedical.experimentnew.bean.FileBean;
import com.example.allshengmedical.experimentnew.bean.FolderBean;

import android.app.Activity;
import android.os.Environment;
import android.util.Log;

/**
 * 
 * @author WillJoe
 * 
 */

public class FileManagerUtil {
	final private String appFilePath = Environment
			.getExternalStorageDirectory() + "/" + "AllShengMedical";

	private ArrayList<FolderBean> folderNames = new ArrayList<FolderBean>();
	private ArrayList<FileBean> fileNames = new ArrayList<FileBean>();
	private ArrayList<FolderBean> searchFolderNames = new ArrayList<FolderBean>();
	private ArrayList<FolderBean> searchFolderOtherNames = new ArrayList<FolderBean>();

	public FileManagerUtil() {
		super();
	}

	public FileManagerUtil(ArrayList<FolderBean> folderNames,
			ArrayList<FileBean> fileNames) {
		super();
		this.folderNames = folderNames;
		this.fileNames = fileNames;
	}

	public ArrayList<FolderBean> getFolderNames() {
		return folderNames;
	}

	public void setFolderNames(ArrayList<FolderBean> folderNames) {
		this.folderNames = folderNames;
	}

	public ArrayList<FileBean> getFileNames() {
		return fileNames;
	}

	public void setFileNames(ArrayList<FileBean> fileNames) {
		this.fileNames = fileNames;
	}

	public ArrayList<FolderBean> getSearchFolderNames() {
		return searchFolderNames;
	}

	public void setSearchFolderNames(ArrayList<FolderBean> searchFolderNames) {
		this.searchFolderNames = searchFolderNames;
	}

	public ArrayList<FolderBean> getSearchFolderOtherNames() {
		return searchFolderOtherNames;
	}

	public void setSearchFolderOtherNames(
			ArrayList<FolderBean> searchFolderOtherNames) {
		this.searchFolderOtherNames = searchFolderOtherNames;
	}

	// 创建默认文件夹
	public void createDefault() {
		String filePath = appFilePath + "/" + "Default";
		File appFile = new File(filePath);
		if (!appFile.exists()) {
			appFile.mkdirs();
		} else {

		}
		String filePath2 = Environment.getExternalStorageDirectory() + "/"
				+ "AllShengReport";
		File appFile2 = new File(filePath2);
		if (!appFile2.exists()) {
			appFile2.mkdirs();
		} else {

		}

	}

	public void createDB() {
		String filePath3 = Environment.getExternalStorageDirectory() + "/"
				+ "AllShengDB";
		File appFile3 = new File(filePath3);
		if (!appFile3.exists()) {
			appFile3.mkdirs();
		} else {

		}

	}

	// 获取具体文件信息
	public void getFileInfo(String fileName) {
		String chosenFilePath = appFilePath + fileName;
		File chosenFile = new File(chosenFilePath);
		File[] chosenFiles = chosenFile.listFiles();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		fileNames = new ArrayList<FileBean>();

		for (int i = 0; i < chosenFiles.length - 1; i++) {
			for (int j = i + 1; j < chosenFiles.length; j++) {
				if (chosenFiles[i].lastModified() < chosenFiles[j]
						.lastModified()) {
					File temp = chosenFiles[i];
					chosenFiles[i] = chosenFiles[j];
					chosenFiles[j] = temp;
				}
			}
		}
		for (int i = 0; i < chosenFiles.length; i++) {
			FileBean fileBean = new FileBean();

			fileBean.setFileName(chosenFiles[i].getName());
			// LogUtil.e(chosenFiles[i].getName());
			fileBean.setCreateTime(format.format(chosenFiles[i].lastModified()));
			fileNames.add(fileBean);

		}

	}

	// 在指定目录下。查看是否有该文件夹，没有就生成文件夹
	public void addFolder(String folderName) {
		String filePath = appFilePath + "/" + folderName;
		File appFile = new File(filePath);
		if (!appFile.exists()) {
			LogUtil.e("正在创建");
			appFile.mkdirs();
		} else {
			LogUtil.e("文件已存在");
		}
		LogUtil.e(filePath);
		getFolderInfo();

		// folderAdapter.upData(folderNames);
		// folderAdapter.upData(folderNames);
		// folderAdapter.notifyDataSetChanged();

	}

	// 获取文件夹信息
	public void getFolderInfo() {
		// File rootFile = Environment.getExternalStorageDirectory();

		File appFile = new File(appFilePath);
		if (!appFile.exists()) {
			LogUtil.e("文件不存在正在创建");
			appFile.mkdirs();
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		File[] appFiles = appFile.listFiles();
		folderNames.clear();
		for (int i = 0; i < appFiles.length; i++) {
			FolderBean folderBean = new FolderBean();
			folderBean.setFolderName(appFiles[i].getName());
			folderBean.setCreateTime(format.format(appFiles[i].lastModified()));
			folderNames.add(folderBean);
			LogUtil.e(appFiles[i].getAbsolutePath());

		}

	}

	// 搜索並且排序
	public void searchAndSort(String result) {

		searchFolderNames = new ArrayList<FolderBean>();
		searchFolderOtherNames = new ArrayList<FolderBean>();

		for (int i = 0; i < folderNames.size(); i++) {

			if (result.equals(folderNames.get(i).getFolderName())) {
				searchFolderNames.add(folderNames.get(i));
			}
		}
		for (int i = 0; i < folderNames.size(); i++) {

			if (result.equals(folderNames.get(i).getFolderName())) {
				continue;
			}
			if (folderNames.get(i).getFolderName().startsWith(result)) {
				searchFolderOtherNames.add(folderNames.get(i));
			}
		}

		Collections.sort(searchFolderOtherNames, new Comparator<FolderBean>() {

			@Override
			public int compare(FolderBean lhs, FolderBean rhs) {
				if (lhs.getFolderName().equals(rhs.getFolderName())) {

					return rhs.getFolderName().compareTo(lhs.getFolderName());
				} else {
					return lhs.getFolderName().compareTo(rhs.getFolderName());
				}

			}
		});

		searchFolderNames.addAll(searchFolderOtherNames);
	}

	// 修改文件名称
	public void updateFolderName(String appOldFolderPath,
			String appNewFolderPath) {
		File appOldFolder = new File(appOldFolderPath);
		File appNewFolder = new File(appNewFolderPath);
		appOldFolder.renameTo(appNewFolder);
	}

	// 修改文件名称
	public void updateFileName(String appOldFilePath, String appNewFilePath) {
		File appOldFile = new File(appOldFilePath);
		File appNewFile = new File(appNewFilePath);
		appOldFile.renameTo(appNewFile);
	}

	// 创建文件
	public void createFIle(String folderName, String fileName) {

		// path表示你所创建文件的路径
		String path = appFilePath + "/" + folderName;
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}

		File file = new File(filePath, fileName);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {

				e.printStackTrace();
			}
		}
		// ByAlert.alert("文件创建成功");
	}

	// 文件的删除
	public void delFIle(String folderName, String fileName) {

		// path表示你所创建文件的路径
		String path = appFilePath + "/" + folderName;
		File filePath = new File(path);
		File file = new File(filePath, fileName);
		if (!file.exists()) {
			file.delete();
		}
	}

	/**
	 * 以字符为单位读取文件，常用于读文本，数字等类型的文件
	 */
	public void readFileByChars(String folderName, String fileName) {
		String path = appFilePath + "/" + folderName;

		File file = new File(path + "/" + fileName);
		Reader reader = null;
		try {
			System.out.println("以字符为单位读取文件内容，一次读一个字节：");
			// 一次读一个字符
			reader = new InputStreamReader(new FileInputStream(file));
			int tempchar;
			while ((tempchar = reader.read()) != -1) {
				// 对于windows下，\r\n这两个字符在一起时，表示一个换行。
				// 但如果这两个字符分开显示时，会换两次行。
				// 因此，屏蔽掉\r，或者屏蔽\n。否则，将会多出很多空行。
				if (((char) tempchar) != '\r') {
					System.out.print((char) tempchar);
				}
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			System.out.println("以字符为单位读取文件内容，一次读多个字节：");
			// 一次读多个字符
			char[] tempchars = new char[30];
			int charread = 0;
			reader = new InputStreamReader(new FileInputStream(fileName));
			// 读入多个字符到字符数组中，charread为一次读取字符数
			while ((charread = reader.read(tempchars)) != -1) {
				// 同样屏蔽掉\r不显示
				if ((charread == tempchars.length)
						&& (tempchars[tempchars.length - 1] != '\r')) {
					System.out.print(tempchars);
				} else {
					for (int i = 0; i < charread; i++) {
						if (tempchars[i] == '\r') {
							continue;
						} else {
							System.out.print(tempchars[i]);
						}
					}
				}
			}

		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	public void readFileByLines(String folderName, String fileName) {

		String path = appFilePath + "/" + folderName;

		File file = new File(path + "/" + fileName);
		BufferedReader reader = null;
		try {
			// System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				System.out.println("line " + line + ": " + tempString);
				Log.e("--", tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	/**
	 * 写文件：使用FileWriter
	 * 
	 * 第三个参数 追加文件内容是 true； 覆盖文件内容是false；
	 * 
	 */
	public void writeFile(String folderName, String fileName, String content,
			Boolean boo) {
		try {
			// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
			String path = appFilePath + "/" + folderName;

			File file = new File(path + "/" + fileName);

			FileWriter writer = new FileWriter(file, boo);
			writer.write(content);
			writer.close();
			// ByAlert.alert("文件保存成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断所要穿件的文件是否存在，如果存在提示更改文件名称
	 * 
	 */
	public boolean fileExist(String folderName, String fileName,
			Activity activity) {
		String path = appFilePath + "/" + folderName;

		File file = new File(path + "/" + fileName);

		if (file.exists()) {
			final AllShengDialog allShengDialog = new AllShengDialog(activity,
					"", "此文件已经创建过，请更换文件名称", "OK");
			allShengDialog.setClicklistener(new ClickListenerInterface() {

				@Override
				public void OK() {
					// TODO Auto-generated method stub
					allShengDialog.dismiss();
				}

				@Override
				public void Cancle() {
					// TODO Auto-generated method stub
					allShengDialog.dismiss();
				}

			});
			allShengDialog.show();
			// ByAlert.alert("此文件已经创建过，请更换文件名称");
			return false;
		} else {
			// ByAlert.alert("名称通过审核");
			// final AllShengDialog allShengDialog = new AllShengDialog(
			// activity, "", "名称通过审核", "OK");
			// allShengDialog.setClicklistener(new ClickListenerInterface() {
			//
			// @Override
			// public void OK() {
			// // TODO Auto-generated method stub
			// allShengDialog.dismiss();
			// }
			//
			// });
			// allShengDialog.show();
			return true;
		}

	}
}
